<template>
    <main class="main-page">
        <template v-if="showHeader">
            <section class="page-section mb-3">
                <div class="container-fluid">
                    <div class="grid justify-content-between align-items-center">
                        <div class="col">
                            <div class="text-2xl text-primary font-bold">
                                选课管理
                            </div>
                        </div>
                        <div class="col-fixed">
                            <template v-if="auth.canView('enrollments/add')">
                                <router-link :to="`/enrollments/add`">
                                    <Button label="添加选课" icon="pi pi-plus" type="button"
                                        class="p-button w-full bg-primary" />
                                </router-link>
                            </template>
                        </div>
                        <div class="col-fixed">
                            <template v-if="auth.canView('enrollments/bulk-import')">
                                <Button label="下载模板" icon="pi pi-download" type="button"
                                    class="p-button w-full bg-primary ml-2" @click="downloadTemplate" />
                            </template>
                        </div>
                        <div class="col-fixed">
                            <template v-if="auth.canView('enrollments/bulk-import')">
                                <Button label="导入选课" icon="pi pi-upload" type="button"
                                    class="p-button w-full bg-primary ml-2" @click="showImportDialog = true" />
                            </template>
                        </div>
                        <div class="col-12 md:col-3">
                            <span class="p-input-icon-left w-full">
                                <i class="pi pi-search" />
                                <InputText :placeholder="$t('search')" class="w-full" :value="filters.search.value"
                                    @input="debounce(() => { filters.search.value = $event.target.value })" />
                            </span>
                        </div>
                    </div>
                </div>
            </section>
        </template>

        <section class="page-section">
            <div class="container-fluid">
                <div class="grid">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <!-- 选课列表 -->
                                <div class="grid">
                                    <div v-for="enrollment in mergedRecords" :key="enrollment.enrollment_id"
                                        class="col-12 md:col-6 lg:col-4 xl:col-3 mb-3">
                                        <EnrollmentCard :enrollment="enrollment" @enrollment-deleted="handleEnrollmentDeleted" />
                                    </div>
                                </div>

                                <!-- 空记录提示 -->
                                <template v-if="pageReady && !mergedRecords.length">
                                    <div class="p-3 my-3 text-500 text-lg font-medium text-center">
                                        {{ $t('noRecordFound') }}
                                    </div>
                                </template>

                                <!-- 分页组件 -->
                                <template v-if="showFooter && pageReady">
                                    <div class="grid justify-content-between align-items-center mt-3">
                                        <div class="col-12">
                                            <Paginator 
                                                class="paginator-flat" 
                                                :first="(localPagination.page - 1) * localPagination.limit"
                                                :rows="localPagination.limit"
                                                :totalRecords="mergedTotalRecords"
                                                :rowsPerPageOptions="[6, 12, 18, 24]"
                                                @page="onPageChange"
                                                :template="'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown'"
                                            >
                                                <template #start>
                                                    <div class="mx-2">
                                                        共 <b>{{ mergedTotalRecords }}</b> 个课程（{{ totalRecords }} 条选课记录）
                                                    </div>
                                                </template>
                                            </Paginator>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 导入对话框 -->
        <Dialog v-model:visible="showImportDialog" :style="{ width: '50vw' }" :header="'导入选课'" :modal="true">
            <FileUpload name="file" mode="basic" @select="onFileSelect" :multiple="false" accept=".xlsx,.xls"
                :maxFileSize="1000000" chooseLabel="选择文件" :auto="false" :showUploadButton="false"
                :showCancelButton="false" dropMessage="将文件拖放到此处上传">
            </FileUpload>

            <DataTable :value="importData" v-if="importData.length" class="mt-3">
                <Column field="student_id" header="学号"></Column>
                <Column field="course_id" header="课程ID"></Column>
                <Column field="course_name" header="课程名称"></Column>
                <Column field="teacher_id" header="教师工号"></Column>
            </DataTable>

            <template #footer>
                <Button label="取消" icon="pi pi-times" @click="showImportDialog = false" class="p-button-text" />
                <Button label="确认导入" icon="pi pi-check" @click="confirmImport" :disabled="!importData.length" />
            </template>
        </Dialog>
    </main>
</template>

<script setup>
import { toRefs, onMounted, ref, computed, nextTick } from 'vue';
import { usePageStore } from 'src/store/page';
import { useApp } from 'src/composables/app.js';
import { useAuth } from 'src/composables/auth';
import { $t } from 'src/services/i18n';
import { useListPage } from 'src/composables/listpage.js';
import { ApiService } from 'src/services/api';
import * as XLSX from 'xlsx';
import { useToast } from 'primevue/usetoast';
import EnrollmentCard from 'src/components/EnrollmentCard.vue';

// PrimeVue 组件导入
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import InputText from 'primevue/inputtext';
import FileUpload from 'primevue/fileupload';
import DataTable from 'primevue/datatable';
import Column from 'primevue/column';
import Paginator from 'primevue/paginator';

const app = useApp();
const auth = useAuth();
const toast = useToast();

const props = defineProps({
    primaryKey: {
        type: String,
        default: 'enrollment_id'
    },
    pageTitle: {
        type: String,
        default: '选课管理'
    },
    routeName: {
        type: String,
        default: 'enrollments'
    },
    apiPath: {
        type: String,
        default: 'enrollments'
    },
    paginate: {
        type: Boolean,
        default: true
    },
    showHeader: {
        type: Boolean,
        default: true
    },
    showFooter: {
        type: Boolean,
        default: true
    },
    showOpt: {
        type: Boolean,
        default: true
    },
    page: {
        type: Number,
        default: 1
    },
    limit: {
        type: Number,
        default: 6
    },
    sortBy: {
        type: String,
        default: ''
    },
    sortType: {
        type: String,
        default: ''
    },
    exportFormats: {
        type: Array,
        default: () => ['pdf', 'excel', 'csv']
    },
    importFormats: {
        type: Array,
        default: () => ['excel', 'csv']
    },
    pageStoreKey: {
        type: String,
        default: 'enrollments/list'
    },
    enableCache: {
        type: Boolean,
        default: true
    },
    mergeRecords: {
        type: Boolean,
        default: false
    },
    search: {
        type: String,
        default: ''
    },
    fieldName: {
        type: String,
        default: null
    },
    fieldValue: {
        type: String,
        default: null
    },
    queryParams: {
        type: Object,
        default: () => ({})
    }
});

const showImportDialog = ref(false);
const importData = ref([]);

const onFileSelect = async (event) => {
    const file = event.files[0];
    const reader = new FileReader();

    reader.onload = (e) => {
        try {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const sheet = workbook.Sheets[workbook.SheetNames[0]];
            const jsonData = XLSX.utils.sheet_to_json(sheet, {
                range: 1,
                raw: false
            });

            importData.value = jsonData;
        } catch (error) {
            console.error('文件处理错误:', error);
            toast.add({ severity: 'error', summary: '错误', detail: '文件处理失败', life: 3000 });
        }
    };

    reader.readAsArrayBuffer(file);
};

const confirmImport = async () => {
    try {
        await ApiService.post('enrollments/bulk-import', importData.value);
        showImportDialog.value = false;
        importData.value = [];
        toast.add({ severity: 'success', summary: '成功', detail: '选课导入成功', life: 3000 });
        load(); // 重新加载数据
    } catch (error) {
        toast.add({ severity: 'error', summary: '错误', detail: '选课导入失败', life: 3000 });
    }
};

const downloadTemplate = async () => {
    try {
        const response = await ApiService.get('enrollments/template', {
            responseType: 'arraybuffer'
        });
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'enrollments_template.xlsx';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
    } catch (error) {
        toast.add({ severity: 'error', summary: '错误', detail: '下载模板失败', life: 3000 });
    }
};

const defaultStoreState = {
    filters: {
        search: {
            tag: "Search",
            value: props.search || '',
            valueType: 'single',
            options: [],
        }
    },
    pagination: {
        page: 1,
        limit: 1000,
        sortBy: props.sortBy,
        sortType: props.sortType
    },
    primaryKey: props.primaryKey,
    enableCache: props.enableCache,
    queryParams: props.queryParams,
    fieldName: props.fieldName,
    fieldValue: props.fieldValue,
    mergeRecords: props.mergeRecords
};

const store = usePageStore(props.pageStoreKey, defaultStoreState);
const page = useListPage({ store, props });
const { records, filters, totalRecords, selectedItems, pagination } = toRefs(store.state);
const { pageReady, loading } = toRefs(page.state);
const { pageBreadCrumb, totalPages, recordsPosition } = page.computedProps;
const { load, exportPage, debounce, onSort, deleteItem } = page.methods;

const mergeEnrollments = (enrollments) => {
    const merged = {};
    enrollments.forEach(enrollment => {
        const key = `${enrollment.course_id}-${enrollment.teacher_id}`;
        if (!merged[key]) {
            merged[key] = {
                ...enrollment,
                student_count: 1,
                student_ids: [enrollment.student_id]
            };
        } else {
            merged[key].student_count++;
            merged[key].student_ids.push(enrollment.student_id);
        }
    });
    return Object.values(merged);
};

const allMergedRecords = computed(() => {
    return mergeEnrollments(records.value || []);
});

const mergedRecords = computed(() => {
    const start = (localPagination.value.page - 1) * localPagination.value.limit;
    const end = start + localPagination.value.limit;
    return allMergedRecords.value.slice(start, end);
});

const mergedTotalRecords = computed(() => {
    return allMergedRecords.value.length;
});

const localPagination = ref({
    page: 1,
    limit: 6
});

const onPageChange = (event) => {
    localPagination.value.page = Math.floor(event.first / event.rows) + 1;
    localPagination.value.limit = event.rows;
};

const handleEnrollmentDeleted = async (result) => {
    if (result.success) {
        // 重新加载数据
        await load();
        
        // 重置分页状态
        localPagination.value = {
            page: 1,
            limit: localPagination.value.limit
        };
        
        // 清空搜索条件
        filters.value.search.value = '';
        
        // 显示成功提示
        if (!result.immediate) { // 如果不是立即刷新的情况才显示提示
            toast.add({ 
                severity: 'success', 
                summary: '成功', 
                detail: `课程"${result.courseName}"的所有选课记录已删除`, 
                life: 3000 
            });
        }
        
        // 强制重新计算合并后的记录
        nextTick(() => {
            mergedRecords.value = mergeEnrollments(records.value || []);
        });
    }
};

onMounted(async () => {
    app.setPageTitle(props.routeName, props.pageTitle);
    try {
        await load();
    } catch (error) {
        console.error('Failed to load data:', error);
        toast.add({ severity: 'error', summary: '错误', detail: '加载数据失败', life: 3000 });
    }
});
</script>

<style scoped>
.enrollment-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1rem;
}
</style>
